package com.ws.wsdemo2.test.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TcpClient {

    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    private static final int READ_IDEL_TIME_OUT = 3; // 读超时
    private static final int WRITE_IDEL_TIME_OUT = 0;// 写超时 0为不启用
    private static final int ALL_IDEL_TIME_OUT = 3;

    public void connect(int port,String host)throws Exception{

        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();

        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                            pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast("handler", new TcpClientHandler());
                        };
                    });

            //发起异步连接操作
            ChannelFuture f = b.connect(host,port).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        }finally{
            //退出，释放资源
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args)throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.TCP_NODELAY, true);//socket配置。禁用Nagel算法，防止数据延迟
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    ByteBuf delimiter = Unpooled.copiedBuffer(Protocol.SPLIT_DELIMITER);
                    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(1024, delimiter));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("handler", new TcpClientHandler());
                }
            });
            Channel ch = b.connect("192.168.12.242", 3125).sync().channel();
            /**
             * ch.closeFuture().sync();作用是：持续监听端口。会使主线程处于wait状态。
             */
            ch.closeFuture().sync();
            ch.close().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

       /* EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        try {
            *//***//*
            b.group(group)
                    *//***//*
                    .channel(NioSocketChannel.class)
                    *//***//*
                    .option(ChannelOption.TCP_NODELAY, true)
                    *//***//*
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer(Protocol.SPLIT_DELIMITER);
                            // 对请求对象进行解码
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                            // ch.pipeline().addLast(new FixedLengthFrameDecoder(1024));
                            // 将ByteBuf解码成字符串对象
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS));
                            // ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            // 注册handler
                            ch.pipeline().addLast(new TcpClientHandler());
                        }
                    });
            // 是否启用心跳保活机制
            b.option(ChannelOption.SO_KEEPALIVE, true);
            // 发起异步连接操作
            System.out.println("############### sync()");
            ChannelFuture f = b.connect("192.168.12.242",3125).sync();
            // 等待客户端链路关闭
            f.channel().closeFuture().sync();
            // this.operationComplete(f);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅退出，释放NIO线程组,需要思考一下还需不需要
            if (group != null) {
                group.shutdownGracefully();
            }
        }*/

        // 所有资源释放完成之后，清空资源，再次发起重连操作
        /*reConnectMarket(port, host);*/

    }




    private void connectMarket(int port, String host) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        try {
            /***/
            b.group(group)
                    /***/
                    .channel(NioSocketChannel.class)
                    /***/
                    .option(ChannelOption.TCP_NODELAY, true)
                    /***/
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer(Protocol.SPLIT_DELIMITER);
                            // 对请求对象进行解码
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                            // ch.pipeline().addLast(new FixedLengthFrameDecoder(1024));
                            // 将ByteBuf解码成字符串对象
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS));
                            // ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            // 注册handler
                            ch.pipeline().addLast(new TcpClientHandler());
                        }
                    });
            // 是否启用心跳保活机制
            b.option(ChannelOption.SO_KEEPALIVE, true);
            // 发起异步连接操作
            System.out.println("############### sync()");
            ChannelFuture f = b.connect(host, port).sync();
            // 等待客户端链路关闭
            f.channel().closeFuture().sync();
            // this.operationComplete(f);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅退出，释放NIO线程组,需要思考一下还需不需要
            if (group != null) {
                group.shutdownGracefully();
            }
        }

        // 所有资源释放完成之后，清空资源，再次发起重连操作
        reConnectMarket(port, host);
    }




    /**
     * 再次发起重连操作
     * @param port
     * @param host
     */
    private void reConnectMarket(final int port, final String host) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    connectMarket(port, host);// 发起重连操作
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}